package com.gingersoft.connect.utils

import android.content.Context
import android.net.nsd.NsdManager
import android.net.nsd.NsdManager.RegistrationListener
import android.net.nsd.NsdServiceInfo
import android.util.Log


class NSDUtils {
    companion object {
        private val TAG = "NSDUtils"
        private val serviceName = "Gingersoft_NSD_KDS"
        private val serviceType = "_http._tcp."
    }

    var registrationListener: NSDRegistrationListener? = null

    fun registerKDS(context: Context) {
        val nsdManager = context.getSystemService(Context.NSD_SERVICE) as NsdManager
        // 先註銷之前的
        unregisterService(context)

        val serviceInfo = NsdServiceInfo()
        serviceInfo.serviceName = serviceName
        serviceInfo.serviceType = serviceType
        serviceInfo.port = 12582
        registrationListener = NSDRegistrationListener()
        // 註冊，這樣KDS才能收到
        nsdManager.registerService(
            serviceInfo,
            NsdManager.PROTOCOL_DNS_SD,
            registrationListener
        )
    }

    class NSDRegistrationListener : RegistrationListener {
        var isRegistered = false // 已註冊

        override fun onRegistrationFailed(nsdServiceInfo: NsdServiceInfo, i: Int) {
            // 註冊失敗處理
            Log.e(TAG, "註冊失敗 ${nsdServiceInfo.host}--$i")
            isRegistered = false
        }

        override fun onUnregistrationFailed(nsdServiceInfo: NsdServiceInfo, i: Int) {
            // 註銷失敗處理
            Log.e(TAG, "註銷失敗 ${nsdServiceInfo.host}--$i")
            isRegistered = false
        }

        override fun onServiceRegistered(nsdServiceInfo: NsdServiceInfo) {
            // 注册成功
            Log.e(TAG, "注册成功 ${nsdServiceInfo.host}--${nsdServiceInfo.serviceName}")
            isRegistered = true
        }

        override fun onServiceUnregistered(nsdServiceInfo: NsdServiceInfo) {
            // 註銷成功處理
            Log.e(TAG, "註銷成功 ${nsdServiceInfo.host}")
            isRegistered = false
        }
    }

    private fun unregisterService(context: Context) {
        if (registrationListener != null && registrationListener!!.isRegistered) {
            try {
                val nsdManager = context.getSystemService(Context.NSD_SERVICE) as NsdManager
                nsdManager.unregisterService(registrationListener)
            } catch (_: IllegalArgumentException) {

            } finally {
                registrationListener = null
            }
        }
    }
}